package com.mysteel.seckill.scheduled;

import com.mysteel.seckill.service.SecondKillService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * ProjectName: mail
 * ClassName: SecKillSkuScheduled
 * Description:秒杀商品定时上架，每天晚上三点，上架最新三天需要秒杀的商品
 * date: 2021/04/07/007 16:02
 *
 * @author xiaochao
 */
@Service
@Slf4j
public class SecKillSkuScheduled {

    @Autowired
    private SecondKillService secondKillService;

    @Autowired
    private RedissonClient redissonClient;

    private static final String SEC_KILL_UPLOAD_LOCK = "sec:kill:upload:lock";

    /**
     * 上架最新三天需要秒杀的商品
     */
    @Scheduled(cron = "0 * * * * ?")
    public void shelvesLatestSecKillProduct(){
        log.info("最近三天秒杀商品上架...");
        // 加入分布式锁，避免多副本定时任务同时启动导致商品重复上架
        RLock lock = redissonClient.getLock(SEC_KILL_UPLOAD_LOCK);
        lock.lock(10, TimeUnit.SECONDS);
        try {
            secondKillService.shelvesLatestSecKillProduct();
        }finally {
            lock.unlock();
        }


    }
}
